package com.bci.pwtz.service.impl;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.exception.ExceptionUtils;
import org.apache.log4j.Logger;
import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;

import com.bci.pwtz.common.ActionCodeConstants;
import com.bci.pwtz.common.PwtzConstants;
import com.bci.pwtz.common.remote.umeng.SendMsgResp;
import com.bci.pwtz.common.util.PaginationList;
import com.bci.pwtz.exception.PwtzDatabaseException;
import com.bci.pwtz.exception.PwtzException;
import com.bci.pwtz.mysql.dao.CompanyMapper;
import com.bci.pwtz.mysql.dao.CompanyRoleActionMapper;
import com.bci.pwtz.mysql.dao.CompanyRoleMapper;
import com.bci.pwtz.mysql.dao.CompanyUserRoleMapper;
import com.bci.pwtz.mysql.dao.UserCompanyRefMapper;
import com.bci.pwtz.mysql.model.Company;
import com.bci.pwtz.mysql.model.CompanyMessage;
import com.bci.pwtz.mysql.model.CompanyRole;
import com.bci.pwtz.mysql.model.CompanyRoleAction;
import com.bci.pwtz.mysql.model.CompanyUser;
import com.bci.pwtz.mysql.model.CompanyUserRole;
import com.bci.pwtz.mysql.model.SmsSendLog;
import com.bci.pwtz.mysql.model.UserCompanyRef;
import com.bci.pwtz.service.CompanyMessageService;
import com.bci.pwtz.service.CompanyService;
import com.bci.pwtz.service.CompanyUserService;
import com.bci.pwtz.service.SmsSendLogService;
import com.bci.pwtz.service.sms.SendSmsService;
import com.bci.pwtz.service.umeng.UMengAppUtilService;

/**
 * 一句话描述 <br/>
 * <p>
 * Description:<br/>
 * <p>
 * TODO 详细描述
 * 
 * <p>
 * For Examples <br/>
 * 
 * <PRE>
 *      TODO 代码使用示例
 * </PRE>
 * <p>
 */
@Service
public class CompanyServiceImpl implements CompanyService
{

    private CompanyMapper companyMapper;
    
    private CompanyRoleMapper companyRoleMapper;
    
    private UserCompanyRefMapper userCompanyRefMapper;
    
    private CompanyRoleActionMapper companyRoleActionMapper;
    
    private CompanyUserRoleMapper companyUserRoleMapper;
    
    private CompanyUserService companyUserService;
    
    private JdbcTemplate jdbcTemplate;
    
    private SendSmsService sendSmsService;
    
    private UMengAppUtilService umengAppUtilService;
    
    private CompanyMessageService companyMessageService;
    
    private SmsSendLogService smsSendLogService;
    /**
     * @return the companyMapper
     */
    public CompanyMapper getCompanyMapper()
    {
        return companyMapper;
    }

    /**
     * @param companyMapper the companyMapper to set
     */
    public void setCompanyMapper(CompanyMapper companyMapper)
    {
        this.companyMapper = companyMapper;
    }
    
    /**
     * @return the companyRoleMapper
     */
    public CompanyRoleMapper getCompanyRoleMapper()
    {
        return companyRoleMapper;
    }

    /**
     * @param companyRoleMapper the companyRoleMapper to set
     */
    public void setCompanyRoleMapper(CompanyRoleMapper companyRoleMapper)
    {
        this.companyRoleMapper = companyRoleMapper;
    }

    
    public UMengAppUtilService getUmengAppUtilService() {
		return umengAppUtilService;
	}

	public void setUmengAppUtilService(UMengAppUtilService umengAppUtilService) {
		this.umengAppUtilService = umengAppUtilService;
	}

	/**
     * @return the userCompanyRefMapper
     */
    public UserCompanyRefMapper getUserCompanyRefMapper()
    {
        return userCompanyRefMapper;
    }

    /**
     * @param userCompanyRefMapper the userCompanyRefMapper to set
     */
    public void setUserCompanyRefMapper(UserCompanyRefMapper userCompanyRefMapper)
    {
        this.userCompanyRefMapper = userCompanyRefMapper;
    }
    
    /**
     * @return the companyRoleActionMapper
     */
    public CompanyRoleActionMapper getCompanyRoleActionMapper()
    {
        return companyRoleActionMapper;
    }

    /**
     * @param companyRoleActionMapper the companyRoleActionMapper to set
     */
    public void setCompanyRoleActionMapper(CompanyRoleActionMapper companyRoleActionMapper)
    {
        this.companyRoleActionMapper = companyRoleActionMapper;
    }

    /**
     * @return the companyUserService
     */
    public CompanyUserService getCompanyUserService()
    {
        return companyUserService;
    }

    /**
     * @param companyUserService the companyUserService to set
     */
    public void setCompanyUserService(CompanyUserService companyUserService)
    {
        this.companyUserService = companyUserService;
    }
    
    
    
    public JdbcTemplate getJdbcTemplate()
    {
        return jdbcTemplate;
    }

    public void setJdbcTemplate(JdbcTemplate jdbcTemplate)
    {
        this.jdbcTemplate = jdbcTemplate;
    }


    public SendSmsService getSendSmsService()
    {
        return sendSmsService;
    }

    public void setSendSmsService(SendSmsService sendSmsService)
    {
        this.sendSmsService = sendSmsService;
    }



    public CompanyMessageService getCompanyMessageService()
    {
        return companyMessageService;
    }

    public void setCompanyMessageService(CompanyMessageService companyMessageService)
    {
        this.companyMessageService = companyMessageService;
    }



    public SmsSendLogService getSmsSendLogService()
    {
        return smsSendLogService;
    }

    public void setSmsSendLogService(SmsSendLogService smsSendLogService)
    {
        this.smsSendLogService = smsSendLogService;
    }
    
    public CompanyUserRoleMapper getCompanyUserRoleMapper()
    {
        return companyUserRoleMapper;
    }

    public void setCompanyUserRoleMapper(CompanyUserRoleMapper companyUserRoleMapper)
    {
        this.companyUserRoleMapper = companyUserRoleMapper;
    }



    private static final Logger _logger = Logger.getLogger(CompanyServiceImpl.class);
    
    @Override
    public Company add(Company company,int type) throws PwtzDatabaseException
    {
        int result=0;
        if (_logger.isDebugEnabled())
        {
            _logger.debug("add:company=" + company.toString());
        }
        if (company == null)
        {
            if (_logger.isDebugEnabled())
            {
                _logger.debug("add,company is null");
            }
            return null;
        }
        try
        {
            if(company!=null){
                company.setStatus(1);
                company.setCreateTime(new Date());
                result = companyMapper.insertSelective(company);
                if(result>0){
                    Long userId =company.getCreatorId();
                    Long companyId = company.getCompanyId();
                    
                    //加入新建单位
                    UserCompanyRef ucr = new UserCompanyRef();
                    ucr.setCompanyId(companyId);
                    ucr.setCompanyUserId(userId);
                    userCompanyRefMapper.insertSelective(ucr);
                    if(type==1){
                        //修改用户最后访问单位
                        CompanyUser companyUser =companyUserService.load(userId);
                        companyUser.setLastCompanyId(companyId);
                        companyUserService.update(companyUser);
                    }
                    
                    //新增管理员角色
                    CompanyRole admin =new CompanyRole();
                    admin.setRoleName("默认管理员分组");
                    admin.setIsSuper(1);
                    admin.setCanDelete(2);
                    admin.setCompanyId(companyId);
                    int ret = companyRoleMapper.insertSelective(admin);
                    if(ret>0){
                        Long roleId = admin.getCompanyRoleId();
//                        String[] str = {"add","del"};
//                        PwtzConstants.DEFAULT_ADMIN_ROLE_ACTION_CODES=str;
                        for(String code:PwtzConstants.DEFAULT_ADMIN_ROLE_ACTION_CODES){
                            CompanyRoleAction cra = new CompanyRoleAction();
                            cra.setActionCode(code);
                            cra.setCompanyRoleId(roleId);
                            companyRoleActionMapper.insertSelective(cra);
                        }
                        CompanyUserRole userrole=new CompanyUserRole();
                        userrole.setCompanyRoleId(roleId);
                        userrole.setCompanyUserId(userId);
                        companyUserRoleMapper.insertSelective(userrole);
                    }
                    
                    //新增用户角色
                    CompanyRole role =new CompanyRole();
                    role.setRoleName("默认用户分组");
                    role.setCanDelete(2);
                    role.setIsSuper(0);
                    role.setCompanyId(companyId);
                    ret = companyRoleMapper.insertSelective(role);
                    if(ret>0){
                        Long roleId = role.getCompanyRoleId();
//                        String[] str = {"add","del","search"};
//                        PwtzConstants.DEFAULT_USER_ROLE_ACTION_CODES=str;
                        for(String code:PwtzConstants.DEFAULT_USER_ROLE_ACTION_CODES){
                            CompanyRoleAction cra = new CompanyRoleAction();
                            cra.setActionCode(code);
                            cra.setCompanyRoleId(roleId);
                            companyRoleActionMapper.insertSelective(cra);
                        }
                    }
                    
                }
            }
        }
        catch (DataAccessException _e)
        {
            _logger.error(ExceptionUtils.getStackTrace(_e));
            throw new PwtzDatabaseException();
        }
        return company;
    }
    
    /* (non-Javadoc)
     * Description: <br/> 
     *
     * @param companyId
     * @return
     * @throws PwtzDatabaseException 
     * @see com.bci.pwtz.service.CompanyService#load(java.lang.Long)
     */
    @Override
    public Company load(Long companyId) throws PwtzDatabaseException
    {
        if (_logger.isInfoEnabled())
        {
            _logger.info("load:companyId=" + companyId);
        }
        Company company = null;
        try
        {
            company = companyMapper.selectCompanyInfo(companyId);
        }
        catch (DataAccessException e)
        {
            _logger.error(ExceptionUtils.getStackTrace(e));
            throw new PwtzDatabaseException();
        }
        if (company != null)
        {
            _logger.debug("load:result company=" + company.toString());
        }
        return company;
    }

    /* (non-Javadoc)
     * Description: <br/> 
     *
     * @param companyId
     * @return
     * @throws PwtzDatabaseException 
     * @see com.bci.pwtz.service.CompanyService#delete(java.lang.Long)
     */
    @Override
    public int delete(Long companyId) throws PwtzDatabaseException
    {
        int result=0;
        if (_logger.isDebugEnabled())
        {
            _logger.debug("delete:companyId=" + companyId);
        }
        try
        {
            result = companyMapper.deleteById(companyId);
        }
        catch (DataAccessException _e)
        {
            _logger.error(ExceptionUtils.getStackTrace(_e));
            throw new PwtzDatabaseException();
        }
        return result;
    }

    /* (non-Javadoc)
     * Description: <br/> 
     *
     * @param company
     * @return 
     * @see com.bci.pwtz.service.CompanyService#updateByPrimaryKey(com.bci.pwtz.mysql.model.Company)
     */
    @Override
    public int update(Company company) throws PwtzDatabaseException
    {
        int result=0;
        if (_logger.isDebugEnabled())
        {
            _logger.debug("update:company=" + company.toString());
        }
        if (company == null)
        {
            if (_logger.isDebugEnabled())
            {
                _logger.debug("update,company is null");
            }
            return 0;
        }
        try
        {
            result = companyMapper.updateByPrimaryKeySelective(company);
        }
        catch (DataAccessException _e)
        {
            _logger.error(ExceptionUtils.getStackTrace(_e));
            throw new PwtzDatabaseException();
        }
        return result;
    }

    @Override
    public List<Company> findCompanyByUserId(Long userId) throws PwtzDatabaseException
    {
        
        if (_logger.isInfoEnabled())
        {
            _logger.info("findCompanyByUserId:|userId=" + userId);
        }

        List<Company> list = null;
        try
        {
                list = companyMapper.findCompanyByUserId(userId);
        }
        catch (DataAccessException e)
        {
            _logger.error(ExceptionUtils.getStackTrace(e));
            throw new PwtzDatabaseException();
        }
        return list;
    }
    
    @Override
    public String findChildrensId(Long companyid,Long userId) throws PwtzDatabaseException{
        List<Long> list = new ArrayList<Long>();
        String Ids=companyid+",";
        try
        {
            list = companyMapper.selectChildrensId(companyid,userId);
        }
        catch (DataAccessException e)
        {
            _logger.error(ExceptionUtils.getStackTrace(e));
            throw new PwtzDatabaseException();
        }
        if(list !=null && list.size()>0){
            for(Long id :list){
                Ids +=findChildrensId(id,userId);
            }
        }
        return Ids;
    }
    
    @Override
    public String findChildren(Long companyid) throws PwtzDatabaseException{
        List<Long> list = new ArrayList<Long>();
        String Ids="";
        try
        {
            list = companyMapper.selectChildrensId(companyid,null);
        }
        catch (DataAccessException e)
        {
            _logger.error(ExceptionUtils.getStackTrace(e));
            throw new PwtzDatabaseException();
        }
        if(list !=null && list.size()>0){
            for(int i=0;i<list.size() ;i++){
                if(i==0){
                    Ids += list.get(i);
                }else{
                    Ids += ","+list.get(i);
                }
            }
        }
        return Ids;
    }
    
    @Override
    public PaginationList<Company> findCompany(String companyName, int pageSize, int pageNo) throws PwtzDatabaseException
    {
        PaginationList<Company> paginationList = new PaginationList<Company>();
        
        if (_logger.isInfoEnabled())
        {
            _logger.info("findCompany:|companyName=" + companyName);
        }
        List<Company> list = null;
        int benginIndex = pageSize * pageNo - pageSize;
        try
        {
            list = companyMapper.selectCompany(companyName,benginIndex, pageSize);
        }
        catch (DataAccessException e)
        {
            _logger.error(ExceptionUtils.getStackTrace(e));
            throw new PwtzDatabaseException();
        }
        if (list!=null)
        {
            _logger.debug("findCompany:result menu=" + list.toString());
        }
        int totalCount = 0;
        int totalPage =1;
        if(pageSize!=0){
            try
            {
                totalCount = companyMapper.selectCompanyNum(companyName);
            }
            catch (DataAccessException e)
            {
                _logger.error(ExceptionUtils.getStackTrace(e));
                throw new PwtzDatabaseException();
            }
            totalPage = totalCount % pageSize == 0 ? totalCount / pageSize : totalCount / pageSize + 1;
        }else{
            pageNo=1;
            if(list!=null && list.size()>0){
                totalCount = list.size();
            }
        }
        paginationList.setTotalPage(totalPage);
        paginationList.setCurrPage(pageNo);
        paginationList.setPageSize(pageSize);
        paginationList.setRecords(list);
        paginationList.setTotalRecord(totalCount);
        return paginationList;
    }

    @Override
    public List<Map<String, Object>> findChildrens(Long companyid, int depth) throws PwtzDatabaseException
    {
        List<Map<String, Object>> retVal = new ArrayList<Map<String, Object>>();
        try
        {            
            Company currentCompany = companyMapper.selectByPrimaryKey(companyid);
            if (currentCompany == null)
                return retVal;

            Map<String, Object> m = new HashMap<String, Object>();
            m.put("companyId",currentCompany.getCompanyId());
            m.put("companyName",currentCompany.getCompanyName());
            m.put("depth",depth);
            retVal.add(m);

            List<Long> list = new ArrayList<Long>();
            list = companyMapper.selectChildrensId(companyid,null);
            if (list != null && list.size() > 0)
            {
                for (Long id : list)
                {
                    retVal.addAll(findChildrens(id, depth + 1));
                }
            }
            return retVal;
        }
        catch (DataAccessException e)
        {
            _logger.error(ExceptionUtils.getStackTrace(e));
            throw new PwtzDatabaseException();
        }
    }
    

    @Override
    public boolean checkSubCompanyValid(List<Map<String,Object>> companys,long checkCompanyId)
    {
        long companyId = 0;
        for(Map<String,Object> m :companys)
        {
            companyId = Long.parseLong(m.get("companyId").toString());
            if(companyId == checkCompanyId)
                return true;
        }
        return false;
    }
    public void sendJoinCompanyValidateSms(long companyUserId,long companyId,long auditId) {
        String actionCode=ActionCodeConstants.COMPANY_USER_AUDIT_MESSAGE_QUERY;
        String selectUserSql="SELECT DISTINCT COMPANY_USER_ID FROM T_COMPANY_USER_ROLE WHERE COMPANY_ROLE_ID in(SELECT DISTINCT COMPANY_ROLE_ID FROM T_COMPANY_ROLE_ACTION WHERE ACTION_CODE=''{0}'')and COMPANY_USER_ID in(SELECT DISTINCT COMPANY_USER_ID FROM T_COMPANY_USER WHERE LAST_COMPANY_ID={1}) UNION SELECT DISTINCT CREATOR_ID FROM T_COMPANY WHERE COMPANY_ID={2}";
        try{
            selectUserSql=MessageFormat.format(selectUserSql, actionCode,companyId,companyId);
            //获取具有审核权限的用户和该公司创建者
            List<Map<String,Object>> retList=jdbcTemplate.queryForList(selectUserSql);
            //获取当前用户信息
            CompanyUser user=companyUserService.load(companyUserId);
            //获取当前公司信息
            Company company=companyMapper.selectByPrimaryKey(companyId);
            if(user==null||company==null){
                return;
            }
            //构建短信内容
            String content=PwtzConstants.JOIN_COMPANY_MSG;
            //构建消息对象
            CompanyMessage companyMessage=new CompanyMessage();
            companyMessage.setAuditId(auditId);
            content=MessageFormat.format(content, user.getLoginName(),company.getCompanyName());
            companyMessage.setMessageType(2);
            companyMessage.setContent(content);
            
            for(Map<String,Object> map:retList){
                Long userId=(Long) map.get("COMPANY_USER_ID");
                CompanyUser companyUser=companyUserService.load(userId);
                //获取该权限用户是否存在或是否具有存有手机号
                if(companyUser==null||companyUser.getMobile()==null){
                    continue;
                }
                companyMessage.setCompanyUserId(userId);
                companyMessageService.add(companyMessage);
                String mobile=companyUser.getMobile();
                String[] mobiles=new String[1];
                mobiles[0]=mobile;
                //发送短信
                String result=sendSmsService.batchSend(mobiles, content, null, null);
                //创建短信日志对象
                
                //判断短信是否发送成功，记录日志
                if("0".equals(result)||"1".equals(result))
                {
                    SmsSendLog smsSendLog=new SmsSendLog();
                    smsSendLog.setMobile(mobile);
                    smsSendLog.setContent(content);
                    smsSendLogService.add(smsSendLog);
                }                
            }
        }catch(DataAccessException e){
            _logger.error(ExceptionUtils.getStackTrace(e));
        }
        catch (UnsupportedEncodingException e)
        {
            _logger.error(ExceptionUtils.getStackTrace(e));
        }
        catch (PwtzException e)
        {
            _logger.error(ExceptionUtils.getStackTrace(e));
        }
        catch (IOException e)
        {
            _logger.error(ExceptionUtils.getStackTrace(e));
        }
    }
    
    
    public void pushMessage(long companyUserId,long companyId) {
        String actionCode=ActionCodeConstants.COMPANY_USER_AUDIT_MESSAGE_QUERY;
        String selectUserSql="SELECT DISTINCT COMPANY_USER_ID FROM T_COMPANY_USER_ROLE WHERE COMPANY_ROLE_ID in(SELECT DISTINCT COMPANY_ROLE_ID FROM T_COMPANY_ROLE_ACTION WHERE ACTION_CODE=''{0}'')and COMPANY_USER_ID in(SELECT DISTINCT COMPANY_USER_ID FROM T_COMPANY_USER WHERE LAST_COMPANY_ID={1}) UNION SELECT DISTINCT CREATOR_ID FROM T_COMPANY WHERE COMPANY_ID={2}";
        try{
            selectUserSql=MessageFormat.format(selectUserSql, actionCode,companyId,companyId);
            //获取具有审核权限的用户和该公司创建者
            List<Map<String,Object>> retList=jdbcTemplate.queryForList(selectUserSql);
            //获取当前用户信息
            CompanyUser user=companyUserService.load(companyUserId);
            //获取当前公司信息
            Company company=companyMapper.selectByPrimaryKey(companyId);
            if(user==null||company==null){
                return;
            }
            
            for(Map<String,Object> map:retList){
                Long userId=(Long) map.get("COMPANY_USER_ID");
                CompanyUser companyUser=companyUserService.load(userId);
                //获取该权限用户是否存在或是否具有存有手机号
                if(companyUser==null||companyUser.getDeviceId()==null){
                    continue;
                }
                String text = user.getLoginName()+"申请加入"+company.getCompanyName()+",请注意审核";
                SendMsgResp resp =  umengAppUtilService.sendAndroidUnicast(companyUser.getDeviceId(), "配网消息", "审核通知", text, "go_app", "notification");
                _logger.debug("推送返回值为"+resp.getRet()+"\n");
                              
            }
        }catch(DataAccessException e){
            _logger.error(ExceptionUtils.getStackTrace(e));
        }
        catch (UnsupportedEncodingException e)
        {
            _logger.error(ExceptionUtils.getStackTrace(e));
        }
        catch (PwtzException e)
        {
            _logger.error(ExceptionUtils.getStackTrace(e));
        }
        catch (IOException e)
        {
            _logger.error(ExceptionUtils.getStackTrace(e));
        } catch (Exception e) {
        	_logger.error(ExceptionUtils.getStackTrace(e));
		}
    }
    

    @Override
    public int selectCreateCompanyNumByUserId(long companyUserId) throws PwtzDatabaseException
    {
        if(_logger.isDebugEnabled()){
            _logger.debug("selectCreateCompanyNumUserId:companyUserId="+companyUserId);
        }
        int result=0;
        try{
            result=companyMapper.selectCreateCompanyNumByUserId(companyUserId);
        }catch(DataAccessException e){
            _logger.error(ExceptionUtils.getStackFrames(e));
            throw new PwtzDatabaseException();
        }
        return result;
    }
    
    
    @Override
    public PaginationList<Company> findCompanyPageByUserId(Long userId, int pageSize, int pageNo) throws PwtzDatabaseException
    {
        PaginationList<Company> paginationList = new PaginationList<Company>();
        
        if (_logger.isInfoEnabled())
        {
            _logger.info("findCompanyPageByUserId:|userId=" + userId);
        }
        List<Company> list = null;
        int benginIndex = pageSize * pageNo - pageSize;
        try
        {
            list = companyMapper.selectCompanyPageByUserId(userId,benginIndex, pageSize);
        }
        catch (DataAccessException e)
        {
            _logger.error(ExceptionUtils.getStackTrace(e));
            throw new PwtzDatabaseException();
        }
        if (list!=null)
        {
            _logger.debug("findCompanyPageByUserId:result menu=" + list.toString());
        }
        int totalCount = 0;
        int totalPage =1;
        if(pageSize!=0){
            try
            {
                totalCount = companyMapper.selectCountCompanyPageByUserId(userId);
            }
            catch (DataAccessException e)
            {
                _logger.error(ExceptionUtils.getStackTrace(e));
                throw new PwtzDatabaseException();
            }
            totalPage = totalCount % pageSize == 0 ? totalCount / pageSize : totalCount / pageSize + 1;
        }else{
            pageNo=1;
            if(list!=null && list.size()>0){
                totalCount = list.size();
            }
        }
        paginationList.setTotalPage(totalPage);
        paginationList.setCurrPage(pageNo);
        paginationList.setPageSize(pageSize);
        paginationList.setRecords(list);
        paginationList.setTotalRecord(totalCount);
        return paginationList;
    }
    
    @Override
    public PaginationList<Company> findMyCompany(Long userId, int pageSize, int pageNo) throws PwtzDatabaseException
    {
        PaginationList<Company> paginationList = new PaginationList<Company>();
        
        if (_logger.isInfoEnabled())
        {
            _logger.info("findCompanyPageByUserId:|userId=" + userId);
        }
        List<Company> rlist = new ArrayList<Company>();
        List<Company> newlist = new ArrayList<Company>();
        List<Company> list = null;
        int benginIndex = pageSize * pageNo - pageSize;
        try
        {
            list = companyMapper.findMyCompany(userId);
            for(Company company:list){
                String ids = findChildrensId(company.getCompanyId(),userId);
                String[] strIds = ids.split(",");
                List<Company> clist = companyMapper.findChildrens(strIds);
                for(Company c:clist){
                    boolean bl =true;
                    for(Company r:rlist){
                        if(r.getCompanyId()==c.getCompanyId()){
                            bl =false;
                            break;
                        }
                    }
                    if(bl){
                        rlist.add(c);
                    }
                }
            }
        }
        catch (DataAccessException e)
        {
            _logger.error(ExceptionUtils.getStackTrace(e));
            throw new PwtzDatabaseException();
        }
        if (rlist==null || rlist.size()==0)
        {
            return paginationList;
        }
        int endIndex =0;
        int totalCount = rlist.size();
        endIndex = pageSize > (totalCount-benginIndex) ? rlist.size():(pageSize+benginIndex);
        for(int i=benginIndex;i<endIndex;i++){
            newlist.add(rlist.get(i));
        }
        int totalPage =1;
        if(pageSize!=0){
            totalPage = totalCount % pageSize == 0 ? totalCount / pageSize : totalCount / pageSize + 1;
        }else{
            pageNo=1;
            if(rlist!=null && rlist.size()>0){
                totalCount = rlist.size();
                newlist = rlist;
            }
        }
        paginationList.setTotalPage(totalPage);
        paginationList.setCurrPage(pageNo);
        paginationList.setPageSize(pageSize);
        paginationList.setRecords(newlist);
        paginationList.setTotalRecord(totalCount);
        return paginationList;
    }
    
    @Override
    public boolean checkIsLowest(long companyId) throws PwtzDatabaseException
    {
        try
        {
            Company company = companyMapper.selectByPrimaryKey(companyId);
            if(company == null)
                return true;
            
            long pid = company.getpId();
            int i=1;
            while(true)
            {
                company = companyMapper.selectByPrimaryKey(pid);
                if(company == null||company.getpId() == 0)
                    break;
                i++;
                pid = company.getpId();
            }
            return i>1;               
        }
        catch(DataAccessException e)
        {
            _logger.error(ExceptionUtils.getStackTrace(e));
            throw new PwtzDatabaseException();
        }
    }

    @Override
    public int selectCompanyCount(Long pid, String name) throws PwtzDatabaseException
    {
        if(_logger.isDebugEnabled()){
            _logger.debug("selectComapnyCount : pid="+pid+",name="+name);
        }
        int result=-1;
        try{
            result=companyMapper.selectCount(pid, name);
        }catch(DataAccessException e){
            _logger.error(ExceptionUtils.getStackTrace(e));
            throw new PwtzDatabaseException();
        }
        return result;
    }
    
    @Override
    public void updateVipExpireStatus() throws PwtzDatabaseException
    {
        if(_logger.isDebugEnabled())
        {
            _logger.debug("updateExpireStatus method start");
        }
        try
        {
            companyMapper.updateVipExpireStatus();
        }
        catch (DataAccessException e)
        {
            _logger.error(ExceptionUtils.getStackTrace(e));
            throw new PwtzDatabaseException();
        }        
    }
    
    @Override
    public boolean isVip(Long companyId) throws PwtzDatabaseException
    {
        if(_logger.isDebugEnabled()){
            _logger.debug("isVip : companyId="+companyId);
        }
        int result=0;
        try{
            result=companyMapper.selectVip(companyId);
        }catch(DataAccessException e){
            _logger.error(ExceptionUtils.getStackTrace(e));
            throw new PwtzDatabaseException();
        }
        return result>0;
    }
}
